package cn.icanci.loopstack.rec.admin.biz.mapper.convertor;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import org.apache.commons.lang3.StringUtils;

/**
 * @author icanci
 * @since 1.0 Created in 2022/11/11 17:03
 */
public abstract class AbstractBaseConverter<T extends Enum<T>> implements BaseConverter<T> {
    @Override
    public String asString(T t) {
        if (t != null) {
            return t.name();
        }
        return null;
    }

    @SuppressWarnings("all")
    @Override
    public T asEnum(String str) {
        if (StringUtils.isBlank(str)) {
            return null;
        }
        Class<? extends AbstractBaseConverter> clazz = getClass();
        Class<T> actualTypeArgument = (Class<T>) GenericSuperclassUtil.getActualTypeArgument(clazz);
        return (T) T.valueOf(actualTypeArgument, str);
    }

    /**
     * 获取泛型类Class对象，不是泛型类则返回null
     */
    private static final class GenericSuperclassUtil {
        public static Class<?> getActualTypeArgument(Class<?> clazz) {
            Class<?> entityClass = null;
            Type genericSuperclass = clazz.getGenericSuperclass();
            if (genericSuperclass instanceof ParameterizedType) {
                Type[] actualTypeArguments = ((ParameterizedType) genericSuperclass).getActualTypeArguments();
                if (actualTypeArguments != null && actualTypeArguments.length > 0) {
                    entityClass = (Class<?>) actualTypeArguments[0];
                }
            }
            return entityClass;
        }
    }
}
